from apscheduler.schedulers.background import BackgroundScheduler
import datetime
import socket
import logging
from django.db import connection
from apps.common.timer.script import *
# from settings.base import DATABASES, BASE_DIR
from apps.pay.financeForLessee.service import financeFun
from apps.pay.recordIncomes.functions import autoFreeBalanceLockedRecord
from apps.merchant.item.views import setSeckillItem

# env = DATABASES.get('default').get('env')

def test():
    connection.close()
    _datetime = datetime.datetime.now()
    print('test----1', _datetime)

def task1():
    print('test----每日00:00:01秒执行', datetime.datetime.now().strftime('%H:%M:%S'))
    connection.close()
    # date = datetime.datetime.now().strftime('%Y-%m-%d')
    # autoFreeBalanceLockedRecord(date)
    # financeFun('day', datetime.datetime.now()-datetime.timedelta(days=1))

def task2():
    print('test----每月第一天00:10:01秒执行', datetime.datetime.now().strftime('%H:%M:%S'))
    connection.close()
    financeFun('month', datetime.datetime.now()-datetime.timedelta(months=1))

def task3():
    print('test----每年第一个月第一天00:20:01秒执行', datetime.datetime.now().strftime('%H:%M:%S'))
    connection.close()
    financeFun('year', datetime.datetime.now()-datetime.timedelta(years=1))

def task4():
    # print('test----每分钟执行', datetime.datetime.now().strftime('%H:%M:%S'))
    connection.close()
    checkOrders()
    # print('test----每分钟执行', datetime.datetime.now().strftime('%H:%M:%S'))

def task5():
    # print('test----每秒执行', datetime.datetime.now())
    connection.close()

def task6():
    print('test----每天下午三点执行', datetime.datetime.now().strftime('%H:%M:%S'))
    connection.close()
    # 在这里添加你需要执行的任务逻辑
    setSeckillItem()
    

try:
    # 利用一个占用端口来检测是否已经启动， 如已占用则说明已启动
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(("127.0.0.1", 45673))
    print()

except:
    print("已启动一个任务计划进程！")
else:
    # 1.实例化调度器
    print("实例化调度器！")
    scheduler = BackgroundScheduler()
    logging.getLogger('apscheduler.executors.default').setLevel(logging.WARNING)

    scheduler.add_job(test, 'cron', hour='23', minute='04', second='5') # 每日00:00:01秒执行
    scheduler.add_job(task1, 'cron', month='1-12',day='1-31', hour='0', minute='0', second='10') # 每日00:00:01秒执行
    scheduler.add_job(task2, 'cron', month='1-12',day='1', hour='0', minute='10', second='10') # 每月第一天00:10:01秒执行
    scheduler.add_job(task3, 'cron', month='1',day='1', hour='0', minute='20', second='10') # 每年第一个月第一天00:20:01秒执行
    scheduler.add_job(task4, 'cron', month='1-12',day='1-31', hour='0-23', minute='0-59', second='01') # 每分钟执行
    scheduler.add_job(task6, 'cron', hour='15', minute='0', second='0')  # 每天下午三点执行

    try:
        scheduler.start()
    except Exception as e:
        # 一般是没生成表，就启动当前程序就会报错
        print('error', e)